<?php
namespace App\Console\Commands\Task;

use App\Repositories\Task\TaskSubmitRepository;
use App\Services\InnerApi;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

use App\Repositories\Task\TaskRepository;

/**
 * 提交任务资料超过审核时间自动标记为通过
 * Class TaskOver
 * @package App\Console\Commands\TaskSubmitApprovalTimeout
 * @version v1.3
 */
class TaskSubmitApprovalTimeout extends Command
{
	protected $signature = 'task:submitApprovalTimeout';

	protected $description = 'Submit record checkout overtime auto change to approvaled';

	private $logger;

	private $taskSubmitRepository;
	private $taskRepository;

	public function __construct(TaskSubmitRepository $taskSubmitRepository, TaskRepository $taskRepository)
	{
		parent::__construct();
		$this->logger = Log::channel('console');
		$this->taskSubmitRepository = $taskSubmitRepository;
		$this->taskRepository = $taskRepository;
	}

	public function handle() {
		$now = time();
		foreach ($this->taskSubmitRepository->getApprovalingRecord() as $record) {
			try {
				$task = $this->taskRepository->getById($record->task_id);
				if ( $now - strtotime($record->addtime) >= $task->approval_time*3600 ) {
					// 审核超时
					$res = InnerApi::request('inner_approval_submit', ['id' => $record->id]);
					if ( empty($res) || $res['data'] != $record->id ) throw new \Exception('Call inner_approval_submit api failed!');
					$this->info($this->signature . "Set submitId:{$record->id} approvaled.");
				}
			} catch (\Exception $e) {
				$this->logger->error($this->signature, [$e->getMessage(), $record->id]);
				$this->error($e->getMessage());
			}
		}

		$this->info($this->signature . ' success！'. (new Carbon())->toDateTimeString());
	}
}